
import json
from sanic import Blueprint, Request, Websocket
import websockets

from app.core.entity import ApiResult
from app.utils.RequestUtils import RequestUtils
from app.websocket.type import WebsocketData

bp=Blueprint("websocket",url_prefix="/")

connectUsers:dict[str,WebsocketData]= {}



async def websocketSendMessage(wsData:WebsocketData,data:dict):
    if data['toUserId']==None:
        await wsData.error(msg="用户ID为空！")
    if data['message']==None or data['message']=="":
        await wsData.error(msg="发送信息不能为空！")
    if connectUsers.get(data['toUserId'])!=None:
        await connectUsers[data['toUserId']].send(data['message'])
    

socketActions={
    "sendMessage":websocketSendMessage,
}

@bp.websocket("/connect")
async def connect(request:Request,ws:Websocket):
    userid=RequestUtils().getCurrentUserId()
    wsData=WebsocketData()
    wsData.websocket=ws
    wsData.currentUserId=RequestUtils().getCurrentUserId()
    connectUsers[userid]=wsData

    try:
        async for msg in ws:
            reqJson=json.loads(msg)
            if reqJson==None or reqJson=="":
                continue
            if reqJson['action']==None:
                await wsData.error(msg="传入方法action")
                continue
            if socketActions[reqJson['action']]==None:
                await wsData.error(msg=f"没有{reqJson['action']}方法！")
                continue
            data=reqJson['data']
            await socketActions[reqJson['action']](wsData,data)
    finally:
        connectUsers[userid]=None
        print("Connection closed")

